import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth.js'
import { login, getUserInfo, getUserDetail } from '@/api/user.js'
const state = {
  token: getToken(),
  userInfo: {} // 可不可以默认定义成null
}
// 同步state数据
const mutations = {
  setToken(state, token) {
    state.token = token // 将token存到vuex
    setToken(token) // 将token 存到本地
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 更新用户信息
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  // 删除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
// 操作异步
const actions = {
  // 登录
  async login(context, data) {
    const result = await login(data) // { header, status, data: { success, message, data } }
    context.commit('setToken', result)
    //  登录成功获取时间戳
    setTimeStamp()
  },
  // 获取用户资料
  async getUserInfo(context) {
    // context 相当于 store
    const res = await getUserInfo()
    const userDetail = await getUserDetail(res.userId)
    const user = { ...res, ...userDetail }
    context.commit('setUserInfo', user)
  }
}
export default {
  namespaced: true, // 命名空间,让模块数据方法私有化
  state,
  mutations,
  actions
}
